package grabber;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.*;
import jxl.write.Number;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class VeloGrabber {
    public static final String BASE_URL = "http://www.alienbike.ru/";
    public static final String BRANDS_URL = "&brand_categories[]=374&brand_categories[]=378&brand_categories[]=405&brand_categories[]=377&brand_categories[]=372&brand_categories[]=396&brand_categories[]=367&brand_categories[]=385&brand_categories[]=386&brand_categories[]=387&brand_categories[]=388&brand_categories[]=400&brand_categories[]=416&brand_categories[]=402";
    private static final int TIMEOUT = 20000;

    public static void main(String[] args) throws IOException, WriteException {
        int offset = 0;
        Document doc = Jsoup.connect(BASE_URL).timeout(TIMEOUT).get();

        Element catElem = doc.select("a[href=http://www.alienbike.ru/schwinn/]").get(0).parent().parent().parent();
        Elements catLinks = catElem.select("a");
        for (Element catLink : catLinks) {
            List<VeloInfo> infoList = new ArrayList<VeloInfo>();
            String linkBrand = catLink.attr("href");
            String brandName = catLink.lastElementSibling().text();
//            if (!brandName.equals("Stels")) {
//                continue;
//            }
            doc = Jsoup.connect(linkBrand).timeout(TIMEOUT).get();
            String brandUrl = doc.select("h3.item-title a:eq(1)").get(0).attr("href");
            while (true) {
                doc = Jsoup.connect(brandUrl + BRANDS_URL + "&offset=" + offset).timeout(TIMEOUT).get();
                if (doc.select("div.l-rnd-inner-cont h3").text().equals("нет товаров")) {
                    break;
                }
                offset += 34;
                Elements productLinks = doc.select("h3.item-title a:lt(1)");
                for (Element productLink : productLinks) {
                    VeloInfo info = new VeloInfo();
                    info.brand = brandName;
                    String linkModel = productLink.attr("href");
                    info.name = productLink.text();
                    System.out.println(info.name);
                    doc = Jsoup.connect(linkModel).timeout(TIMEOUT).get();
                    Elements elements = doc.select("div.l-col-pad p");
                    for (Element elem : elements) {
                        if (elem.text().length() < 5) {
                            continue;
                        } else if (elem.text().startsWith("Цена")) {
                            try {
                                info.price = Integer.parseInt(elem.text().split(" ")[1].replace(",", ""));
                            } catch (NumberFormatException e) {
                                info.price = 0;
                            }
                            System.out.println(info.price);
                        } else if (elem.text().startsWith("Техническое описание")) {
                            info.techDesc = elem.toString().trim();
                            System.out.println(info.techDesc);
                        } else if (!elem.text().startsWith("Торфяная дорога") &&
                                !elem.text().startsWith("Наличие на складе") &&
                                !elem.text().startsWith("(голосов")) {
                            info.desc = elem.text().trim();
                            System.out.println(info.desc);
                        }
                    }
                    info.cat = doc.select("p.l-rnd-inner-cont a:eq(2)").text();
                    System.out.println(info.cat);
                    infoList.add(info);
                }
            }
            infoToFile(brandName, infoList);
        }
    }

    private static void infoToFile(String brandName, List<VeloInfo> infoList) throws IOException, WriteException {
        File xlsFile = new File("data/velo/" + brandName + ".xls");
        WorkbookSettings s = new WorkbookSettings();
        WritableWorkbook workbook = Workbook.createWorkbook(xlsFile, s);
        workbook.createSheet("sheet", 0);
        WritableSheet sheet = workbook.getSheet(0);
        int row = 0;
        for (VeloInfo info : infoList) {
            sheet.addCell(new Label(0, row, info.brand));
            sheet.addCell(new Label(1, row,  info.name));
            sheet.addCell(new Label(2, row,  info.cat));
            sheet.addCell(new Number(3, row,  info.price));
            sheet.addCell(new Label(4, row,  info.techDesc));
            sheet.addCell(new Label(5, row,  info.desc));
            row++;
        }
        workbook.write();
        workbook.close();
    }

    static class VeloInfo {
        String brand;
        String name;
        int price;
        String techDesc;
        String desc;
        String cat;
    }

}
